package juc.lock;

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: zhs
 * @since: 2021/6/30 16:40
 */
public class TestCon {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        ArrayList<Integer> ans = new ArrayList<>();
        Thread thread1 = new Thread(() -> {
            while (true){
                try {
                    lock.lock();
                    if(ans.size()==10){
                        condition.await();
                    }
                    ans.add(1);
                    condition.signal();
                    System.out.println("produce"+ans);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread thread = new Thread(() -> {
            while (true){
                try {
                    lock.lock();
                    if(ans.size()==0){
                        condition.await();
                    }
                    ans.remove(0);
                    condition.signal();
                    System.out.println("consume"+ans);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        thread.start();
        thread1.start();


        thread.join();
        thread1.join();

    }
}
